/*******************************************************************************
 * Copyright 2011 Mauro Luigi Drago (drago.luigi@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.bytenose.extrautils.patterns.observer;

import java.util.Collection;

import com.bytenose.extrautils.annotations.NonNullable;
import com.bytenose.extrautils.base.IDisposable;

/**
 * A default implementation of an unsubscriber which can be used by:
 * <ul>
 * 	<li>Observers to unsubscribe by invoking {@link Unsubscriber#dispose()}
 *  <li>Observables when receiving a subscription request. 
 * </ul>
 * @author Mauro Luigi Drago
 *
 * @param <T> the type of the observed object.
 */
public final class Unsubscriber<T> implements IDisposable {
	/** The collection of observers */
	private final Collection<IObserver<T>> observers;
	
	/** The observer */
	private final IObserver<T> observer;
	
	/**
	 * Creates a new {@link Unsubscriber}.
	 * @param observers the list of observers, cannot be null.
	 * @param observer the observer, cannot be null.
	 * @throws IllegalArgumentException 
	 * 		if some of the {@link NonNullable} arguments are null.
	 * 
	 */
	public Unsubscriber(@NonNullable Collection<IObserver<T>> observers, 
			@NonNullable IObserver<T> observer) 
			throws IllegalArgumentException {
		if (observers == null) throw new IllegalArgumentException("observers");
		if (observer == null) throw new IllegalArgumentException("observer");
		this.observers = observers;
		this.observer = observer;
	}
	
	/**
	 * Removes the observer from the list of observers.
	 * See also {@link IDisposable#dispose()}
	 */
	@Override
	public void dispose() {
		if (observer != null && observers.contains(observer))
			observers.remove(observer);
	}
	
	/**
	 * Creates a new {@link Unsubscriber}.
	 * @param <T> the type of the observed object.
	 * @param observers the list of observers, cannot be null.
	 * @param observer the observer, cannot be null.
	 * @return the new object.
	 * @throws IllegalArgumentException 
	 * 		if some of the {@link NonNullable} arguments are null. 
	 */
	@NonNullable
	public static <T> Unsubscriber<T> newInstance(
			@NonNullable Collection<IObserver<T>> observers, 
			@NonNullable IObserver<T> observer) 
			throws IllegalArgumentException {
		return new Unsubscriber<T>(observers, observer);
	}
}
